<?php
// +----------------------------------------------------------------------
// | YBlog
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://www.neatcn.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: gouki <neatstudio@yahoo.com.cn>
// | Modify: yhustc <yhustc@gmail.com>
// +----------------------------------------------------------------------
// $Id$

/**
 +------------------------------------------------------------------------------
 * 发送邮件类
 +------------------------------------------------------------------------------
 * @category   ORG
 * @package  ORG
 * @author    gouki <neatstudio@yahoo.com.cn>
 * @Modify    yhustc <yhustc@gmail.com>
 * @version   $Id$
 +------------------------------------------------------------------------------
 */
class Mail extends Base
{
	/**
     +----------------------------------------------------------
     * SMTP服务器地址
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */
    protected $server = 'smtp.163.com';
    /**
     +----------------------------------------------------------
     * SMTP服务器端口
     +----------------------------------------------------------
     * @var integer
     * @access protected
     +----------------------------------------------------------
     */
    protected $port = 25;
    /**
     +----------------------------------------------------------
     * SMTP服务器是否需要认证
     +----------------------------------------------------------
     * @var integer
     * @access protected
     +----------------------------------------------------------
     */
    protected $auth = 1;
    /**
     +----------------------------------------------------------
     * 发件人名称
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */
    protected $from = 'admin <admin@163.com>'; //一定要是这种格式，否则可能发不出去
	/**
     +----------------------------------------------------------
     * 登录SMTP服务器的用户名
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */
    protected $auth_username = 'admin'; //一般不用加域，如果发不出去就尝试加上域看看
	/**
     +----------------------------------------------------------
     * 登录SMTP服务器的密码
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */ 
    protected $auth_password = 'password';
	/**
     +----------------------------------------------------------
     * 断行符是用还是\r还是\n,1为,2为\r其它为\n
     +----------------------------------------------------------
     * @var integer
     * @access protected
     +----------------------------------------------------------
     */ 
    protected $maildelimiter = 0;
    /**
     +----------------------------------------------------------
     * 是否显示发信人名字
     +----------------------------------------------------------
     * @var integer
     * @access protected
     +----------------------------------------------------------
     */ 
    protected $mailusername = 1;
	/**
     +----------------------------------------------------------
     * 邮件使用的字符集
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */ 
    protected $charset = 'utf-8'; //如果这里改成了gbk，那么，本文件一定要另存为ansi格式
    /**
     +----------------------------------------------------------
     * 显示在邮箱的发件人
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */ 
    protected $adminname = 'admin';
    /**
     +----------------------------------------------------------
     * 发件人的邮件地址
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */ 
    protected $adminemail = 'admin@163.com';
    /**
     +----------------------------------------------------------
     * 主题的前缀
     +----------------------------------------------------------
     * @var string
     * @access protected
     +----------------------------------------------------------
     */ 
	protected $actName = '新评论';
	
	/**
     +----------------------------------------------------------
     * 构造函数
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @param 
     +----------------------------------------------------------
     */
	function __construct() {
		$options = S("options");
		$this->server = $options["mailserver_url"];
		$this->port = $options["mailserver_port"];
		$this->from = substr($options["mailserver_email"],0,strpos($options["mailserver_email"],"@"))." <".$options["mailserver_email"].">";
		$this->auth_username = $options["mailserver_login"];
		$this->auth_password = $options["mailserver_pass"];
		$this->adminname = substr($options["mailserver_email"],0,strpos($options["mailserver_email"],"@"));
		$this->adminemail = $options["mailserver_email"];
	}
	
	/**
     +----------------------------------------------------------
     * 记录错误日志函数
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @param string $type	错误类型
     * @param string $info	错误信息
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
	function errorlog ($type='',$info=''){   
			$data = '['.$type.']'.$info . "\n";   
			file_put_contents('mail_log.txt', $data , FILE_APPEND);   
	}	
	
	/**
     +----------------------------------------------------------
     * 发送邮件函数
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     * @param string $email_to	邮件接收者,格式为'admin <admin@qq.com>',多个接收者使用,隔开
     * @param string $email_subject	邮件主题
     * @param string $email_message  邮件正文
     * @param string $email_from  邮件发送者的名字
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
	function sendmail ($email_to, $email_subject, $email_message, $email_from = ''){ 
		$maildelimiter = $this->maildelimiter == 1 ? "" : ($this->maildelimiter == 2 ? "\r" : "\n");   
		$mailusername = isset($this->mailusername) ? $this->mailusername : 1;   
	   
		$email_subject = '=?'.$this->charset.'?B?'.base64_encode(str_replace("\r", '', str_replace("\n", '', '['.$this->actName.'] '.$email_subject))).'?=';   
		$email_message = chunk_split(base64_encode(str_replace(".", " ..", str_replace("\n", "", str_replace("\r", "\n", str_replace("", "\n", str_replace("\n\r", "\r", $email_message)))))));   
	   
		$email_from = $email_from == '' ? '=?'.$this->charset.'?B?'.base64_encode($this->adminname)."?= <$this->adminemail>" : (preg_match('/^(.+?) \<(.+?)\>$/',$email_from, $from) ? '=?'.$this->charset.'?B?'.base64_encode($from[1])."?= <$from[2]>" : $email_from);   
	   
		foreach(explode(',', $email_to) as $touser) {   
			$tousers[] = preg_match('/^(.+?) \<(.+?)\>$/',$touser, $to) ? ($mailusername ? '=?'.$this->charset.'?B?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser;   
		}   
		$email_to = implode(',', $tousers);   
	   
		$headers = "From: $email_from{$maildelimiter}X-Priority: 3{$maildelimiter}X-Mailer: Gouki! {$maildelimiter}MIME-Version: 1.0{$maildelimiter}Content-type: text/plain; charset={$this->charset}{$maildelimiter}Content-Transfer-Encoding: base64{$maildelimiter}";   
	   
		$this->port = $this->port ? $this->port : 25;   
	   
		if(!$fp = fsockopen($this->server, $this->port, $errno, $errstr, 20)) {   
			$this->errorlog('SMTP', "($this->server:$this->port) CONNECT - Unable to connect to the SMTP server", 0);   
		}   
		stream_set_blocking($fp, true);   
	   
		$lastmessage = fgets($fp, 512);   
		if(substr($lastmessage, 0, 3) != '220') {   
			$this->errorlog('SMTP', "$this->server:$this->port CONNECT - $lastmessage", 0);   
		}   
	   
		fputs($fp, ($this->auth ? 'EHLO' : 'HELO')." YBlog\r\n");   
		$lastmessage = fgets($fp, 512);   
		if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {   
			$this->errorlog('SMTP', "($this->server:$this->port) HELO/EHLO - $lastmessage", 0);   
		}   
	   
		while(1) {   
			if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {   
				break;   
			}   
			$lastmessage = fgets($fp, 512);   
		}   
	   
		if($this->auth) {   
			fputs($fp, "AUTH LOGIN\r\n");   
			$lastmessage = fgets($fp, 512);   
			if(substr($lastmessage, 0, 3) != 334) {   
				$this->errorlog('SMTP', "($this->server:$this->port) AUTH LOGIN - $lastmessage", 0);   
			}   
	   
			fputs($fp, base64_encode($this->auth_username)."\r\n");   
			$lastmessage = fgets($fp, 512);   
			if(substr($lastmessage, 0, 3) != 334) {   
				$this->errorlog('SMTP', "($this->server:$this->port) USERNAME - $lastmessage", 0);   
			}   
	   
			fputs($fp, base64_encode($this->auth_password)."\r\n");   
			$lastmessage = fgets($fp, 512);   
			if(substr($lastmessage, 0, 3) != 235) {   
				$this->errorlog('SMTP', "($this->server:$this->port) PASSWORD - $lastmessage", 0);   
			}   
	   
			$email_from = $this->from;   
		}   
	   
		fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");   
		$lastmessage = fgets($fp, 512);   
		if(substr($lastmessage, 0, 3) != 250) {   
			fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");   
			$lastmessage = fgets($fp, 512);   
			if(substr($lastmessage, 0, 3) != 250) {   
				$this->errorlog('SMTP', "($this->server:$this->port) MAIL FROM - $lastmessage", 0);   
			}   
		}   
	   
		$email_tos = array();   
		foreach(explode(',', $email_to) as $touser) {   
			$touser = trim($touser);   
			if($touser) {   
				fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");   
				$lastmessage = fgets($fp, 512);   
				if(substr($lastmessage, 0, 3) != 250) {   
					fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");   
					$lastmessage = fgets($fp, 512);   
					$this->errorlog('SMTP', "($this->server:$this->port) RCPT TO - $lastmessage", 0);   
				}   
			}   
		}   
	   
		fputs($fp, "DATA\r\n");   
		$lastmessage = fgets($fp, 512);   
		if(substr($lastmessage, 0, 3) != 354) {   
			$this->errorlog('SMTP', "($this->server:$this->port) DATA - $lastmessage", 0);   
		}   
	   
		$headers .= 'Message-ID: <'.gmdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$maildelimiter}";   
	   
		fputs($fp, "Date: ".gmdate('r')."\r\n");   
		fputs($fp, "To: ".$email_to."\r\n");   
		fputs($fp, "Subject: ".$email_subject."\r\n");   
		fputs($fp, $headers."\r\n");   
		fputs($fp, "\r\n");   
		fputs($fp, "$email_message\r\n\r\n.\r\n");   
		fputs($fp, "QUIT\r\n");
		
		fclose($fp);
	}
}
?>